package com.pm.demo.controller;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.util.*;


@RestController
@EnableAutoConfiguration
public class PmController {
    @GetMapping(value = "/pm")
     public Map<String,List<String>> getPm(){
        Map<String,List<String>> list=new HashMap<>();
        try
        {

            Document document = Jsoup.connect("http://pm25.in/handan").get();
//            等级
            Elements h4=document.getElementsByTag("h4");
            list.put("level",getText(h4));
//            更新时间
            Elements times=document.getElementsByClass("live_data_time");
            list.put("time",getText(times.get(0)));
//            单位
            Elements units=document.getElementsByClass("live_data_unit");
            list.put("units",getText(times.get(0)));

            Elements data=document.select(".data .value");
            list.put("data",getText(data));
            Elements caption=document.select(".data .caption");
            list.put("caption",getText(caption));

            Elements ths=document.getElementsByTag("th");
            list.put("tableTitle",getText(ths));
            Elements tds=document.getElementsByTag("td");
            list.put("td",getText(tds));
//            提取表格数据
            Elements scripts=document.getElementsByTag("script");
            String s= String.valueOf(scripts.get(5));
            s = s.replaceAll("\r|\n", "");//去掉换行
            s = s.replaceAll(" ", "");//去掉空格
            int index1=s.indexOf("categories:[");
            s=s.substring(index1+13);
            String temp1=s.substring(0,s.indexOf("\"]"));
            String[] time_array=temp1.split("\",\"");
            list.put("table_item", Arrays.asList(time_array));

            int index2=s.indexOf("data:[");
            s=s.substring(index2+6);
            String temp2=s.substring(0,s.indexOf("]"));
            String[] time_data=temp2.split(",");
            list.put("table_data", Arrays.asList(time_data));

        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return list;
    }

    private List<String> getText(Elements elements){
        List<String> list=new ArrayList<>();
        for (Element element:elements) {
            list.add(element.text());
        }
        return list;
    }
    private List<String> getText(Element element){
        List<String> list=new ArrayList<>();
        list.add(element.text());
        return list;
    }
}
